// V-backend/src/controllers/cartController.js
const db = require('../models');
const Cart = db.Cart;
const Product = db.Product;
const { Op } = require('sequelize');

// 获取用户购物车
exports.getUserCart = async (req, res) => {
  try {
    const audience_id = req.user.userId; // 从token中获取用户ID
    
    console.log('🛒 获取购物车，用户ID:', audience_id);
    
    const cartItems = await Cart.findAll({
      where: { audience_id },
      include: [
        {
          model: Product,
          as: 'product',
          attributes: ['product_id', 'product_name', 'product_description', 'price', 'cover_image', 'stock_quantity', 'status'],
          include: [
            {
              model: db.Anchor,
              as: 'anchor',
              attributes: ['anchor_id', 'anchor_name']
            }
          ]
        }
      ],
      order: [['created_at', 'DESC']]
    });
    
    console.log('📦 查询到的购物车项:', cartItems.length);
    
    // 过滤掉已下架或库存为0的商品
    const validCartItems = cartItems.filter(item => 
      item.product && 
      item.product.status === 'active' && 
      item.product.stock_quantity > 0
    );
    
    // 计算总价和总数量
    let total = 0;
    let totalQuantity = 0;
    
    validCartItems.forEach(item => {
      const itemTotal = item.quantity * parseFloat(item.product.price);
      total += itemTotal;
      totalQuantity += item.quantity;
    });
    
    // 格式化返回数据，适配前端
    const formattedItems = validCartItems.map(item => ({
      id: item.cart_id,  // 前端期望的字段名
      cart_id: item.cart_id,
      product_id: item.product_id,
      quantity: item.quantity,
      product: {
        id: item.product.product_id,  // 前端期望的字段名
        product_id: item.product.product_id,
        name: item.product.product_name,  // 前端期望的字段名
        product_name: item.product.product_name,
        description: item.product.product_description,
        price: item.product.price,
        stock: item.product.stock_quantity,  // 前端期望的字段名
        stock_quantity: item.product.stock_quantity,
        cover_image: item.product.cover_image,
        anchor: item.product.anchor
      }
    }));
    
    res.json({
      code: 200,
      success: true,
      message: '获取购物车成功',
      data: {
        items: formattedItems,
        summary: {
          total: total.toFixed(2),
          totalQuantity: totalQuantity,
          itemCount: validCartItems.length
        }
      }
    });
  } catch (error) {
    console.error('❌ 获取购物车失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '获取购物车失败',
      error: error.message
    });
  }
};

// 添加商品到购物车
exports.addToCart = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    const { product_id, quantity = 1 } = req.body;
    
    console.log('🛒 添加购物车，用户:', audience_id, '商品:', product_id, '数量:', quantity);
    
    if (!product_id) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '缺少商品ID'
      });
    }
    
    // 检查商品是否存在且有库存
    const product = await Product.findByPk(product_id);
    if (!product) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '商品不存在'
      });
    }
    
    if (product.status !== 'active') {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '商品已下架'
      });
    }
    
    if (product.stock_quantity <= 0) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '商品库存不足'
      });
    }
    
    // 检查是否已在购物车中
    let cartItem = await Cart.findOne({
      where: { audience_id, product_id }
    });
    
    if (cartItem) {
      // 更新数量，但不能超过库存
      const newQuantity = cartItem.quantity + parseInt(quantity);
      if (newQuantity > product.stock_quantity) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: `库存不足，最多可购买 ${product.stock_quantity} 件`
        });
      }
      
      cartItem.quantity = newQuantity;
      await cartItem.save();
    } else {
      // 创建新记录
      if (quantity > product.stock_quantity) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: `库存不足，最多可购买 ${product.stock_quantity} 件`
        });
      }
      
      cartItem = await Cart.create({
        audience_id,
        product_id,
        quantity: parseInt(quantity)
      });
    }
    
    // 返回完整的购物车项信息
    const cartItemWithProduct = await Cart.findByPk(cartItem.cart_id, {
      include: [
        {
          model: Product,
          as: 'product',
          attributes: ['product_id', 'product_name', 'product_description', 'price', 'cover_image', 'stock_quantity'],
          include: [
            {
              model: db.Anchor,
              as: 'anchor',
              attributes: ['anchor_id', 'anchor_name']
            }
          ]
        }
      ]
    });
    
    // 格式化返回数据
    const formattedItem = {
      id: cartItemWithProduct.cart_id,
      cart_id: cartItemWithProduct.cart_id,
      product_id: cartItemWithProduct.product_id,
      quantity: cartItemWithProduct.quantity,
      product: {
        id: cartItemWithProduct.product.product_id,
        product_id: cartItemWithProduct.product.product_id,
        name: cartItemWithProduct.product.product_name,
        product_name: cartItemWithProduct.product.product_name,
        description: cartItemWithProduct.product.product_description,
        price: cartItemWithProduct.product.price,
        stock: cartItemWithProduct.product.stock_quantity,
        stock_quantity: cartItemWithProduct.product.stock_quantity,
        cover_image: cartItemWithProduct.product.cover_image,
        anchor: cartItemWithProduct.product.anchor
      }
    };
    
    res.json({
      code: 200,
      success: true,
      message: '添加购物车成功',
      data: formattedItem
    });
  } catch (error) {
    console.error('❌ 添加购物车失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '添加购物车失败',
      error: error.message
    });
  }
};

// 更新购物车商品数量
exports.updateCartItem = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    const { cart_id } = req.params;
    const { quantity } = req.body;
    
    console.log('🛒 更新购物车，ID:', cart_id, '数量:', quantity);
    
    if (!quantity || quantity < 1) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '数量必须大于0'
      });
    }
    
    const cartItem = await Cart.findOne({
      where: { cart_id, audience_id },
      include: [{
        model: Product,
        as: 'product'
      }]
    });
    
    if (!cartItem) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '购物车商品不存在'
      });
    }
    
    // 检查库存
    if (quantity > cartItem.product.stock_quantity) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: `库存不足，最多可购买 ${cartItem.product.stock_quantity} 件`
      });
    }
    
    cartItem.quantity = parseInt(quantity);
    await cartItem.save();
    
    res.json({
      code: 200,
      success: true,
      message: '更新购物车成功',
      data: cartItem
    });
  } catch (error) {
    console.error('❌ 更新购物车失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '更新购物车失败',
      error: error.message
    });
  }
};

// 删除购物车商品
exports.removeFromCart = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    const { cart_id } = req.params;
    
    console.log('🛒 删除购物车商品，ID:', cart_id);
    
    const cartItem = await Cart.findOne({
      where: { cart_id, audience_id }
    });
    
    if (!cartItem) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '购物车商品不存在'
      });
    }
    
    await cartItem.destroy();
    
    res.json({
      code: 200,
      success: true,
      message: '删除购物车商品成功'
    });
  } catch (error) {
    console.error('❌ 删除购物车商品失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '删除购物车商品失败',
      error: error.message
    });
  }
};

// 清空购物车
exports.clearCart = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    
    console.log('🛒 清空购物车，用户:', audience_id);
    
    await Cart.destroy({
      where: { audience_id }
    });
    
    res.json({
      code: 200,
      success: true,
      message: '清空购物车成功'
    });
  } catch (error) {
    console.error('❌ 清空购物车失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '清空购物车失败',
      error: error.message
    });
  }
};

// 获取购物车商品数量
exports.getCartCount = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    
    console.log('🛒 获取购物车数量，用户:', audience_id);
    
    const cartCount = await Cart.count({
      where: { audience_id },
      include: [{
        model: Product,
        as: 'product',
        where: {
          status: 'active',
          stock_quantity: { [Op.gt]: 0 }
        }
      }]
    });
    
    res.json({
      code: 200,
      success: true,
      message: '获取购物车数量成功',
      data: {
        count: cartCount
      }
    });
  } catch (error) {
    console.error('❌ 获取购物车数量失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '获取购物车数量失败',
      error: error.message
    });
  }
};